package com.lee.rpc.protocal.netty;

import com.lee.rpc.protocal.code.RpcDecode;
import com.lee.rpc.protocal.code.RpcEncode;
import com.lee.rpc.protocal.core.RpcProtocal;
import com.lee.rpc.protocal.core.RpcRequest;
import com.lee.rpc.protocal.netty.handler.ClientHandler;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

public class NettyClient {

	private String serviceAddress;
	private int port;
	private EventLoopGroup eventLoop;
	private Bootstrap bootstrap;

	public NettyClient(String host, int port) {
		eventLoop = new NioEventLoopGroup();
		bootstrap = new Bootstrap();
		bootstrap.group(eventLoop).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {
			@Override
			protected void initChannel(SocketChannel ch) throws Exception {
				// TODO Auto-generated method stub
				ch.pipeline()
					.addLast(new RpcEncode())
					.addLast(new RpcDecode())
					.addLast(new ClientHandler());
			}
		});
		this.serviceAddress = host;
		this.port = port;
	}

	public void sendRequest(RpcProtocal<RpcRequest> protocol) throws InterruptedException {
		ChannelFuture channelFuture = bootstrap.connect(serviceAddress, port).sync(); 
		channelFuture.addListener(new ChannelFutureListener() { 
			@Override
			public void operationComplete(ChannelFuture future) throws Exception {
				// TODO Auto-generated method stub
				if(future.isSuccess()) {
					System.out.println("connect rpc server "+(serviceAddress+":"+port)+" success");
				}else {
					System.out.println("connect rpc server "+(serviceAddress+":"+port)+" failed");
					channelFuture.cause().printStackTrace();
					eventLoop.shutdownGracefully();
				}
			}
		});
		//向服务端写数据 
		channelFuture.channel().writeAndFlush(protocol);
	}
}
